/****************************************************
          File Name:17-7.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue Jan 20 23:04:42 2015
*****************************************************/

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<algorithm>

using namespace std;

void Showstr(string &s)
{
    cout << s << endl;
}

class Store
{
    public:
        ostream & out;
        Store(ostream & fout) : out(fout) {};
        void operator()(string &s)
        {
            out.write(s.c_str(), s.size());
            out.write("\n", 1);
        }
};

void GetStrs(istream & fin, vector<string>vistr)
{
    string tmp;
    size_t len;
    while(fin.read((char *)&len, sizeof(size_t)) && len > 0)
    {
        char ch;
        tmp = "";
        for(int j = 0; j < len; j++)
        {
            if(fin.read(&ch, 1))
                tmp += ch;
            else
                break;
        }
        if(fin)
            vistr.push_back(tmp);
    }
}

int main()
{
    vector<string> vostr;
    string tmp;

    // acquire strings
    cout << "Enter string (empty line to quit):\n";
    while(getline(cin, tmp) && tmp[0] != '\0')
        vostr.push_back(tmp);
    cout << "Here is your input.\n";
    for_each(vostr.begin(), vostr.end(), Showstr);

    // store in a file
    ofstream fout("string.dat", ios_base::out | ios_base::binary);
    for_each(vostr.begin(), vostr.end(), Store(fout));

    // recover file contents
    vector<string> vistr;
    ifstream fin("string.dat", ios_base::in | ios_base::binary);
    if(!fin.is_open())
    {
        cerr << "Could not open file for input\n";
        exit(EXIT_FAILURE);
    }
    GetStrs(fin, vistr);
    cout << "\nHere are the strings read from the file:\n";
    for_each(vistr.begin(), vistr.end(), Showstr);

    return 0;
}
